package com.lagou.edu.service.impl;


import com.lagou.edu.dao.LagouAuthCodeDao;
import com.lagou.edu.entity.LagouAuthCode;
import com.lagou.edu.service.CodeService;
import com.lagou.edu.service.EmailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;
import java.util.Random;

@Service
public class CodeServiceImpl implements CodeService {

    @Autowired
    private EmailService emailService;

    @Autowired
    private LagouAuthCodeDao lagouAuthCodeDao;

    //校验验证码是否正确，0正确1错误2超时
    @Override
    public Integer validate(String email, String code) {

        LagouAuthCode lagouAuthCode = new LagouAuthCode();
        lagouAuthCode.setEmail(email);
        List<LagouAuthCode> all = lagouAuthCodeDao.findAll(Example.of(lagouAuthCode));
        // 10分钟失效
        LocalDateTime localDateTime = LocalDateTime.now().minusMinutes(10);
        Date date = Date.from(localDateTime.atZone(ZoneId.systemDefault()).toInstant());

        // 没有验证码 或者验证码失效 验证码错误
        if (!ObjectUtils.isEmpty(all)) {
            lagouAuthCode = all.get(0);
            if (lagouAuthCode.getExpiretime().getTime() < date.getTime()) {
                return 2;
            }
            if (!lagouAuthCode.getCode().equals(code)) {
                return 1;
            }
        }
        return 0;
    }

    @Override
    public Boolean create(String email) {
        LagouAuthCode lagouAuthCode = new LagouAuthCode();
        Random random = new Random();
        int code = random.nextInt(999999);
        String code_text = String.format("%6d", code).replace(" ", "0");
        // 发送邮箱
        Boolean flag = emailService.email(email, code_text);
        if (!flag) {
            return flag;
        }
        // 存储数据
        lagouAuthCode.setCode(code_text);
        lagouAuthCode.setCreatetime(new Date());
        lagouAuthCode.setExpiretime(new Date());
        lagouAuthCode.setEmail(email);
        lagouAuthCodeDao.save(lagouAuthCode);
        return true;
    }

}
